@inject IFileVersionProvider Version
@inject IHttpContextAccessor HttpContextAccessor

@if (ChildContent == null)
{
    <link rel="stylesheet" @attributes="AdditionalAttributes" />
}
else
{
    <style @attributes="AdditionalAttributes" nonce="@Nonce">@ChildContent</style>
}

@code {
    [Parameter(CaptureUnmatchedValues = true)]
    public Dictionary<string, object> AdditionalAttributes { get; set; } = new();
    
    [Parameter]
    public RenderFragment? ChildContent { get; set; }
    
    protected override void OnInitialized()
    {
        if (AdditionalAttributes.ContainsKey("href"))
        {
            AdditionalAttributes["href"] = Version.Get(AdditionalAttributes["href"].ToString()!);
        }
    }
    
    public string? Nonce
    {
        get
        {
            if (HttpContextAccessor.HttpContext?.Items == null)
            {
                return null;
            }
            
            if (HttpContextAccessor.HttpContext!.Items.TryGetValue("csp-nonce", out var nonce))
            {
                return nonce?.ToString();
            }

            return null;
        }
    }
}